package com.midongtech.cpd;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.midongtech.cpd.adapter.AdListAdapter;
import com.midongtech.cpd.bean.AppData;
import com.midongtech.cpd.bean.ResponseAppsData;
import com.midongtech.cpd.constants.MonitorConstant;
import com.midongtech.cpd.utils.AppUtils;
import com.midongtech.cpd.utils.CommonCallBack;
import com.midongtech.cpd.utils.HttpManager;

import java.util.ArrayList;
import java.util.List;

public class TaskActivity extends AppCompatActivity implements TaskRefresh {

    private Activity mActiviy;
    private Context mContext;
    private Gson mGson;
    private ProgressBar pb_loading;
    private SwipeRefreshLayout swipeLayout;
    private RecyclerView mRecyclerView;
    private AdListAdapter adListAdapter;
    private AppInstallReceiver receiver;
    public static List<AppData> sDataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        mActiviy = this;
        mContext = getApplicationContext();
        mGson = new Gson();
        initViews();
        initReceiver();
        getData();

        if (!AppUtils.isUsagePermissionAceess(mContext)) {
            showToast("请设置app的使用情况访问权限");
            startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
        }

    }

    private void initViews() {
        pb_loading = findViewById(R.id.pb_loading);
        swipeLayout = findViewById(R.id.swipeLayout);
        mRecyclerView = findViewById(R.id.recyclerview);
        LinearLayoutManager manager = new LinearLayoutManager(mActiviy);
        manager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
        adListAdapter = new AdListAdapter(mActiviy, null,this);
        mRecyclerView.setAdapter(adListAdapter);

        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

    }

    private void getData() {
        HttpManager.getAds(mContext, new CommonCallBack() {
            @Override
            public void onSuccess(String response) {
                Log.e("cpd", "getAds onSuccess:" + response);
                ResponseAppsData responseAppsData = mGson.fromJson(response, ResponseAppsData.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(false);
                        pb_loading.setVisibility(View.GONE);
                        if (responseAppsData != null && responseAppsData.getData() != null && responseAppsData.getData().size() > 0) {
                            sDataList = responseAppsData.getData();
                            adListAdapter.setData(sDataList);
                        } else {
                            showToast("数据为空");
                        }
                    }
                });


            }

            @Override
            public void onFailure(String response) {
                Log.e("cpd", "getAds onFailure:" + response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(false);
                    }
                });
                showToast("数据加载失败：" + response);
            }
        });
    }

    private void initReceiver() {
        if (receiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.intent.action.PACKAGE_ADDED");
            filter.addAction("android.intent.action.PACKAGE_REPLACED");
            filter.addAction("android.intent.action.PACKAGE_REMOVED");
            filter.addDataScheme("package");
            receiver = new AppInstallReceiver();
            mContext.registerReceiver(receiver, filter);
        }
    }

    private void destoryReceiver() {
        if (receiver == null) {
            mContext.unregisterReceiver(receiver);
        }
    }

    private void showToast(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
            }
        });
    }

    public static AppData getAppDataByPkg(String pkg) {
        for (AppData data : sDataList ) {
            if (data.getPkg().equals(pkg)) {
                return data;
            }
        }
        return null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryReceiver();
        adListAdapter.mHandler.removeCallbacksAndMessages(null);
        adListAdapter.mHandler = null;
    }


    @Override
    public void onrefresh() {
        getData();
    }


    class AppInstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("AppInstallReceiver", "context:" + context + "intent:" + intent.getAction());
            if (context != null && intent.getAction() != null && intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
                String packageName = intent.getDataString();
                if (!TextUtils.isEmpty(packageName) && packageName.contains("package:")) {
                    packageName = packageName.replace("package:", "");
                }
                showToast(packageName + " 安装成功");
                HttpManager.monitor(mContext, getAppDataByPkg(packageName), MonitorConstant.INSTALL_FINISH, null);

            }
        }
    }
}

